<template>
  <div class="analytics">
    <!-- 数据概览 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="item in overviewData" :key="item.title">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon" :style="{ backgroundColor: item.color }">
                <el-icon :size="24">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-value">{{ item.value }}</div>
                <div class="card-trend" :class="item.trend > 0 ? 'positive' : 'negative'">
                  <el-icon>
                    <ArrowUp v-if="item.trend > 0" />
                    <ArrowDown v-else />
                  </el-icon>
                  {{ Math.abs(item.trend) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 销售趋势 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">销售趋势</span>
                <el-select v-model="salesTrendPeriod" size="small" style="width: 120px">
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                  <el-option label="最近90天" value="90d" />
                </el-select>
              </div>
            </template>
            <div ref="salesTrendChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 客户分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户地区分布</span>
            </template>
            <div ref="customerDistributionChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 产品销售排行 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">产品销售排行</span>
            </template>
            <div ref="productRankingChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 客户价值分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户价值分析</span>
            </template>
            <div ref="customerValueChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 月度收入分析 -->
        <el-col :xs="24" :lg="16">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">月度收入分析</span>
                <el-date-picker
                  v-model="revenueYear"
                  type="year"
                  placeholder="选择年份"
                  size="small"
                  style="width: 120px"
                  @change="updateRevenueChart"
                />
              </div>
            </template>
            <div ref="revenueChart" class="chart-container" style="height: 350px"></div>
          </el-card>
        </el-col>

        <!-- 订单状态分布 -->
        <el-col :xs="24" :lg="8">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">订单状态分布</span>
            </template>
            <div ref="orderStatusChart" class="chart-container" style="height: 350px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-tables">
      <el-row :gutter="20">
        <!-- 热销产品 -->
        <el-col :xs="24" :lg="12">
          <el-card class="table-card">
            <template #header>
              <span class="card-title">热销产品</span>
            </template>
            <el-table :data="hotProducts" stripe>
              <el-table-column prop="rank" label="排名" width="60" align="center" />
              <el-table-column prop="name" label="产品名称" />
              <el-table-column prop="sales" label="销量" width="80" align="right" />
              <el-table-column prop="revenue" label="收入" width="100" align="right">
                <template #default="{ row }"> ¥{{ formatAmount(row.revenue) }} </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 优质客户 -->
        <el-col :xs="24" :lg="12">
          <el-card class="table-card">
            <template #header>
              <span class="card-title">优质客户</span>
            </template>
            <el-table :data="topCustomers" stripe>
              <el-table-column prop="rank" label="排名" width="60" align="center" />
              <el-table-column prop="name" label="客户名称" />
              <el-table-column prop="orders" label="订单数" width="80" align="right" />
              <el-table-column prop="amount" label="消费金额" width="120" align="right">
                <template #default="{ row }"> ¥{{ formatAmount(row.amount) }} </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { TrendCharts, User, ShoppingCart, Money, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { formatAmount } from '@/utils'

// 图表实例
const salesTrendChart = ref<HTMLElement>()
const customerDistributionChart = ref<HTMLElement>()
const productRankingChart = ref<HTMLElement>()
const customerValueChart = ref<HTMLElement>()
const revenueChart = ref<HTMLElement>()
const orderStatusChart = ref<HTMLElement>()

let salesTrendChartInstance: echarts.ECharts
let customerDistributionChartInstance: echarts.ECharts
let productRankingChartInstance: echarts.ECharts
let customerValueChartInstance: echarts.ECharts
let revenueChartInstance: echarts.ECharts
let orderStatusChartInstance: echarts.ECharts

// 数据
const salesTrendPeriod = ref('30d')
const revenueYear = ref(new Date())

// 概览数据
const overviewData = ref([
  {
    title: '总销售额',
    value: '¥2,456,789',
    trend: 12.5,
    icon: 'Money',
    color: '#67C23A',
  },
  {
    title: '新增客户',
    value: '156',
    trend: 8.2,
    icon: 'User',
    color: '#409EFF',
  },
  {
    title: '订单总数',
    value: '1,234',
    trend: -2.1,
    icon: 'ShoppingCart',
    color: '#E6A23C',
  },
  {
    title: '转化率',
    value: '68.5%',
    trend: 5.3,
    icon: 'TrendCharts',
    color: '#F56C6C',
  },
])

// 热销产品数据
const hotProducts = ref([
  { rank: 1, name: '真丝面料', sales: 245, revenue: 123000 },
  { rank: 2, name: '棉麻混纺', sales: 198, revenue: 89000 },
  { rank: 3, name: '羊毛呢料', sales: 167, revenue: 156000 },
  { rank: 4, name: '涤纶面料', sales: 134, revenue: 45000 },
  { rank: 5, name: '亚麻面料', sales: 98, revenue: 67000 },
])

// 优质客户数据
const topCustomers = ref([
  { rank: 1, name: '上海时装有限公司', orders: 45, amount: 234000 },
  { rank: 2, name: '北京服饰集团', orders: 38, amount: 198000 },
  { rank: 3, name: '广州纺织厂', orders: 32, amount: 167000 },
  { rank: 4, name: '深圳制衣公司', orders: 28, amount: 145000 },
  { rank: 5, name: '杭州丝绸企业', orders: 25, amount: 123000 },
])

// 初始化销售趋势图表
const initSalesTrendChart = () => {
  if (!salesTrendChart.value) return

  salesTrendChartInstance = echarts.init(salesTrendChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
    },
    legend: {
      data: ['销售额', '订单数'],
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(万元)',
        position: 'left',
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
      },
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 0,
        data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
        smooth: true,
        itemStyle: {
          color: '#409EFF',
        },
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: [45, 52, 38, 48, 35, 78, 69, 58, 62, 78, 89, 95],
        itemStyle: {
          color: '#67C23A',
        },
      },
    ],
  }

  salesTrendChartInstance.setOption(option)
}

// 初始化客户分布图表
const initCustomerDistributionChart = () => {
  if (!customerDistributionChart.value) return

  customerDistributionChartInstance = echarts.init(customerDistributionChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '客户分布',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 335, name: '华东地区' },
          { value: 310, name: '华南地区' },
          { value: 234, name: '华北地区' },
          { value: 135, name: '西南地区' },
          { value: 148, name: '其他地区' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  customerDistributionChartInstance.setOption(option)
}

// 初始化产品排行图表
const initProductRankingChart = () => {
  if (!productRankingChart.value) return

  productRankingChartInstance = echarts.init(productRankingChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: ['亚麻面料', '涤纶面料', '羊毛呢料', '棉麻混纺', '真丝面料'],
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: [98, 134, 167, 198, 245],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
      },
    ],
  }

  productRankingChartInstance.setOption(option)
}

// 初始化客户价值图表
const initCustomerValueChart = () => {
  if (!customerValueChart.value) return

  customerValueChartInstance = echarts.init(customerValueChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      top: '5%',
      left: 'center',
    },
    series: [
      {
        name: '客户价值',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 45, name: '高价值客户' },
          { value: 35, name: '中价值客户' },
          { value: 20, name: '低价值客户' },
        ],
      },
    ],
  }

  customerValueChartInstance.setOption(option)
}

// 初始化收入图表
const initRevenueChart = () => {
  if (!revenueChart.value) return

  revenueChartInstance = echarts.init(revenueChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['收入', '利润'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '收入',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series',
        },
        data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
      },
      {
        name: '利润',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series',
        },
        data: [30, 35, 25, 35, 22, 58, 52, 45, 48, 58, 72, 82],
      },
    ],
  }

  revenueChartInstance.setOption(option)
}

// 初始化订单状态图表
const initOrderStatusChart = () => {
  if (!orderStatusChart.value) return

  orderStatusChartInstance = echarts.init(orderStatusChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 45, name: '已完成' },
          { value: 25, name: '进行中' },
          { value: 15, name: '待确认' },
          { value: 10, name: '已取消' },
          { value: 5, name: '已退款' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  orderStatusChartInstance.setOption(option)
}

// 更新收入图表
const updateRevenueChart = () => {
  // 这里可以根据选择的年份更新数据
  console.log('更新收入图表:', revenueYear.value)
}

// 监听销售趋势周期变化
watch(salesTrendPeriod, () => {
  // 这里可以根据选择的周期更新数据
  console.log('更新销售趋势:', salesTrendPeriod.value)
})

// 窗口大小变化时重新调整图表
const handleResize = () => {
  salesTrendChartInstance?.resize()
  customerDistributionChartInstance?.resize()
  productRankingChartInstance?.resize()
  customerValueChartInstance?.resize()
  revenueChartInstance?.resize()
  orderStatusChartInstance?.resize()
}

onMounted(async () => {
  await nextTick()

  // 初始化所有图表
  initSalesTrendChart()
  initCustomerDistributionChart()
  initProductRankingChart()
  initCustomerValueChart()
  initRevenueChart()
  initOrderStatusChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.analytics {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.data-tables {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    margin-bottom: 16px;
  }

  .card-content {
    flex-direction: column;
    text-align: center;
  }

  .card-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .chart-container {
    height: 250px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
